import DialogView from "../components/DialogView.vue";
import type { DialogParams } from "../../api/test/index.d";

// 确保Element Plus样式被引入
import "element-plus/dist/index.css";

export default function createDialog({
  config,
  bizData,
  onCallback
}: {
  config: Partial<DialogParams>;
  bizData: any;
  onCallback?: (params: any) => Promise<void>;
}) {
  console.log("封装后的createDialogsdasdfsdafsfsad", config, bizData, onCallback);
  const parentNode = document.createElement("div");
  document.body.appendChild(parentNode);

  const cleanup = () => {
    if (appInstance) {
      appInstance.unmount();
    }
    if (parentNode.parentNode) {
      parentNode.parentNode.removeChild(parentNode);
    }
  };

  let appInstance: any = null;

  // 创建应用实例的通用函数
  const createAppInstance = (createApp: any) => {
    appInstance = createApp(DialogView, {
      config,
      bizData,
      onCallback,
      modelValue: true,
      onClose: () => cleanup()
    });

    // 确保Element Plus组件可用
    try {
      // 动态导入Element Plus
      import("element-plus")
        .then(({ default: ElementPlus }) => {
          appInstance.use(ElementPlus);
          appInstance.mount(parentNode);
        })
        .catch(() => {
          // 如果Element Plus导入失败，直接挂载
          console.warn("Element Plus auto-import failed, mounting without styles");
          appInstance.mount(parentNode);
        });
    } catch (error) {
      console.warn("Element Plus registration failed:", error);
      appInstance.mount(parentNode);
    }
  };

  // 获取Vue创建函数
  const getVueCreateApp = () => {
    // 1. 优先使用平台Vue
    if ((window as any).Vue?.createApp) {
      return (window as any).Vue.createApp;
    }

    // 2. 使用模块自己的Vue
    return import("vue").then(({ createApp }) => createApp);
  };

  // 启动弹窗
  getVueCreateApp()
    .then((createApp: any) => {
      createAppInstance(createApp);
    })
    .catch((error: any) => {
      console.error("Failed to create dialog:", error);
      cleanup();
    });

  return cleanup; // 返回清理函数
}
